﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Text;
using Microsoft.SharePoint;
using System.Xml;

using SharePointEnforcer.Utilities;

namespace SharePointEnforcer
{
    /// <summary>
    /// Main Entry Point for Rule Processing
    /// </summary>
    class SPEnforcer
    {
        private RuleManager _manager;
        private EnforcerSettings _settings;

        public SPEnforcer(string[] pArgs) : this(EnforcerCommandArgs.ProcessArgs(pArgs)) { }
        public SPEnforcer(EnforcerSettings pSettings)
        {
            _settings = pSettings;
            _manager = new RuleManager(_settings);
        }

        public void EvaluateRules()
        {
            foreach (string rulePath in _settings.RulesPaths)
            {
                Begin(rulePath);
            }
        }

        private void Begin(string pathToStarterFile)
        {
            RuleStarter starter = new RuleStarter(pathToStarterFile);

            foreach (SiteRuleNode site in starter.Sites)
            {
                CrawlSite(site);
            }
        }

        private void CrawlSite(SiteRuleNode starterSite)
        {
            using (SPSite site = new SPSite(starterSite.SiteUrl.AbsoluteUri))
            {
                using (SPWeb web = site.OpenWeb("/"))
                {
                    ProcessRules(web);
                }
            }
        }


        private void ProcessRules(SPWeb pWeb)
        {
            // ~~ process web rules here
            _manager.ProcessRules(pWeb);
            //~~  Should also see if there is away to reduce this.  i.e. if a node has onlydefined rules at the top level then there is no need 
            // to iterate through child nodes

            SPWebCollection childWebs = pWeb.Webs;
            foreach (SPWeb childWeb in childWebs)
            {
                ProcessRules(childWeb);
            }
        }

    }


}